import pymysql
import re
from datetime import datetime, date
import decimal
import json


class QianMysql():
    def __init__(self, option):
        self.option = option

    def connect(self):
        self.conn = pymysql.connect(**self.option)
        self.cursor = self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def format_line_sql(self, query):
        return re.sub(r'\s+', ' ', query.replace('\n', ' '))


    def get_one(self, sql, *args):
        result = None
        try:
            self.connect()
            self.cursor.execute(sql, args)
            result = self.cursor.fetchone()
            self.close()
        except Exception as e:
            print(sql)
            print(args)
            print(e)
        return result


    def get_all(self, sql, *args):
        result = ()
        try:
            self.connect()
            self.cursor.execute(sql, args)
            result = self.cursor.fetchall()
            self.close()
        except Exception as e:
            print(sql)
            print(args)
            print(e)
        return result

    def __edit(self, sql, args):
        count = 0
        try:
            self.connect()
            count = self.cursor.execute(sql, args)
            self.conn.commit()
            self.close()
        except Exception as e:
            print(sql)
            print(args)
            # app.logger.info(self.format_line_sql(self.cursor.mogrify(sql, args)))
            print(e)
        return count

    def insert(self, sql, *args):
        return self.__edit(sql, args)

    def update(self, sql, *args):
        return self.__edit(sql, args)

    def delete(self, sql, *args):
        return self.__edit(sql, args)


class DateEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(float(o))
        else:
            return json.JSONEncoder.default(self, o)